<?php
namespace Category\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Category\Model\Category;
use Category\Form\CategoryForm;


class CategoryController extends AbstractActionController
{
    protected $categoryTable;

    public function indexAction()
    {
	return new ViewModel(array(
	   'allCategory' => $this->getCategoryTable()->fetchAll(), 
	));
    }
    
    public function addAction()
    {
	$form = new CategoryForm();
	$request = $this->getRequest();
	$form->get('submit')->setValue('Add category');
	if ($request->isPost()) {
	    $category = new Category();
	    $form->setInputFilter($category->getInputFilter());
	    $form->setData($request->getPost());
	    if ($form->isValid()) {
		$category->exchangeArray($form->getData());
		$this->getCategoryTable()->saveCategory($category);
		return $this->redirect()->toRoute('category');
	    } else {
	    }
	}
	return array('form' => $form);
    }
    
    public function editAction()
    {
	$id = (int) $this->params()->fromRoute('id',0);
	if (!$id) {
	    return $this->redirect()->toRoute('category', array(
		'action' => 'add',
	    ));
	}
	try {
	    $category = $this->getCategoryTable()->getCategory($id);
	}
	catch (\Exception $ex) {
	    return $this->redirect()->toRoute('category', array(
		'action' => 'index',
	    ));
	}

	$form = new CategoryForm();
	$form->bind($category);
	$form->get('submit')->setValue('Save');

	$request = $this->getRequest();
	if ($request->isPost()) {
	    $form->setInputFilter($category->getInputFilter());
	    $form->setData($request->getPost());

	    if ($form->isValid()) {
		$this->getCategoryTable()->saveCategory($form->getData());
		return $this->redirect()->toRoute('category');
	    }
	}
	return array(
	    'id' => $id,
	    'form' => $form,
	);
    }
    
    public function deleteAction()
    {
	$id = $this->params()->fromRoute('id',0);
	if (!$id) {
	    $this->redirect('category');
	}
	
	$request = $this->getRequest();
	if ($request->isPost()) {
	    $del = $request->getPost('del', 'No');
	    if ($del === 'Yes') {
		$id = (int) $request->getPost('id');
		/* @var $categoryTable \Category\Model\CategoryTable */
		$categoryTable = $this->getCategoryTable();
		$categoryTable->getSql();
		
	    }
	    return $this->redirect()->toRoute('category');
	}
	
	return array(
	    'id' => $id,
	    'category' => $this->getCategoryTable()->getCategory($id),
	);
    }
    
    public function getCategoryTable()
    {
	if (!$this->categoryTable) {
	    $sm = $this->getServiceLocator();
	    $this->categoryTable = $sm->get('Category\Model\CategoryTable');
	}
	return $this->categoryTable;
    }
}